package com.qf.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.test.annotation.Commit;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @After:最终增强，无论是否有异常都执行
 * @AfterReturning:后置增强，如果有异常不执行
 *
 * @author YDW
 * projectName:project2202_3
 * time:2022/5/6 22:14
 * description:
 */
@Aspect
@Component
public class AopConfig {
    @Autowired
    private DataSource dataSource;

    //切入点表达式
    @Pointcut("execution(* com.qf.service.impl.*.*(..))")
    public void pc(){}

//    //增强
//    @Before("pc()")
//    public void before(){
//        System.out.println("在方法执行之前执行");
//    }
//    @After("pc()")
//    public void after(){
//        System.out.println("在方法执行之后执行 01");
//    }
//    @AfterReturning("pc()")
//    public void afterReturning(){
//        System.out.println("在方法执行之后执行 02");
//    }
//    @AfterThrowing("pc()")
//    public void afterThrowing(){
//        System.out.println("在出现异常后执行");
//    }


    //环绕增强: 调用原始方法(如果没有调用原始方法，原始方法内容不执行)
    //ProceedingJoinPoint 连接点对象（被拦截的方法）
//    @Around("pc()")
//    @Transactional()
//    public Object around(ProceedingJoinPoint joinPoint){
//        Connection connection=null;
//        try {
//            connection=dataSource.getConnection();
//            connection.setAutoCommit(false);
//
//            Object result = joinPoint.proceed();
//
//            connection.commit();
//            return  result;
//        } catch (Throwable e) {
//            try {
//                connection.rollback();
//            } catch (SQLException ex) {
//                ex.printStackTrace();
//            }
//            throw new RuntimeException(e);
//
//        }finally {
//            try {
//                connection.close();
//            } catch (SQLException e) {
//                e.printStackTrace();
//            }
//        }
//    }
    @Around("pc()")
    public Object around(ProceedingJoinPoint joinPoint){
        try {
            System.out.println("前置");
            Object result = joinPoint.proceed();
            System.out.println("后置");
            return result;
        } catch (Throwable e) {
            System.out.println("异常");
            throw new RuntimeException(e);
        } finally {
            System.out.println("最终");
        }
    }
}
